package relation

import (
	"gostore/dao"
	"gostore/model"
)

type RolePolicyDaoT struct {
	dao.DaoT
}

var RolePolicyDao = RolePolicyDaoT{}

func (RolePolicyDaoT) LoadAllWithRolePolicy(list *[]model.RelationRolePolicy) error {
	rows, err := dao.GetDB().Raw("select rel.id, rel.role_id, rel.policy_id , p.path, p.name, p.method, r.id from eb_relation_role_policy rel " +
		" left join eb_system_role r on r.id=rel.role_id left join eb_system_policy p on p.id=rel.policy_id").Rows()
	if err != nil {
		return err
	}

	for rows.Next() {
		rel := model.RelationRolePolicy{}
		err = rows.Scan(&rel.Id, &rel.RoleId, &rel.PolicyId, &rel.Policy.Path, &rel.Policy.Name, &rel.Policy.Method, &rel.Role.Id)
		// log.Debug(rel)
		if err != nil {
			return err
		}

		*list = append(*list, rel)
	}
	return nil
}

func (RolePolicyDaoT) LoadAllWithRolePolicyByRole(list *[]model.RelationRolePolicy, roleIdstr string) error {
	rows, err := dao.GetDB().Raw("select rel.id, rel.role_id, rel.policy_id , p.path, p.name, p.method, r.id from eb_relation_role_policy rel " +
		" left join eb_system_role r on r.id=rel.role_id left join eb_system_policy p on p.id=rel.policy_id where rel.role_id in (" + roleIdstr + ")").Rows()
	if err != nil {
		return err
	}

	for rows.Next() {
		rel := model.RelationRolePolicy{}
		err = rows.Scan(&rel.Id, &rel.RoleId, &rel.PolicyId, &rel.Policy.Path, &rel.Policy.Name, &rel.Policy.Method, &rel.Role.Id)
		// log.Debug(rel)
		if err != nil {
			return err
		}

		*list = append(*list, rel)
	}
	return nil
}
